import { defineStore } from 'pinia';
import { Session } from '/@/utils/storage';
import useLoginApi from '../api/login';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
    state: (): UserInfosState => ({
        userInfos: {
            userName: '',
            photo: '',
            time: 0,
            roles: [],
            authBtnList: []
        }
    }),
    actions: {
        async setUserInfos() {
            // 存储用户信息到浏览器缓存
            if (Session.get('userInfo')) {
                this.userInfos = Session.get('userInfo');
            } else {
                const userInfos = <UserInfos>await this.getApiUserInfo();
                this.userInfos = userInfos;
            }
        },
        async getApiUserInfo() {
            return useLoginApi
                .getUserInfo()
                .then((res: any) => {
					const userInfoRes = res.data;
                    const userInfos = {
                        userName: userInfoRes.user.nickName,
                        photo: 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                        time: new Date().getTime(),
                        roles: userInfoRes.user.roles,
                        authBtnList: userInfoRes.permissions,
						userMetaData: userInfoRes.user
                    };
                    Session.set('userInfo', userInfos);
                    return userInfos;
                });
        }
    }
});
